package morning.cat.demo.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.plugin.activerecord.Page;
import morning.cat.demo.entity.User;

import java.util.List;

/**
 * XXX
 *
 * @author mengzhang6
 * @date 2018/12/7 13:38
 */
public class UserController extends Controller {

    public void save() {
        // 创建name属性为James,age属性为25的User对象并添加到数据库
        boolean result = new User().set("name", "James").set("age", 25).save();
        renderText(String.valueOf(result));
    }

    public void update() {
        // 查询id值为25的User将其name属性改为James并更新到数据库
        boolean result = User.dao.findById(25).set("name", "Mengxxx").update();
        renderText(String.valueOf(result));
    }

    public void findById() {
        User user = User.dao.findById(25);
        renderText(user.toJson());
    }

    public void findByIdLoadColumns() {
        // 查询id值为25的user, 且仅仅取name与age两个字段的值
        User user = User.dao.findByIdLoadColumns(25, "name, age");

        // 获取user的name属性
        String userName = user.getStr("name");
        // 获取user的age属性
        Integer userAge = user.getInt("age");
        renderText(user.toJson());
        System.out.println(userName + " " + userAge);
    }

    public void find() {
        // 查询所有年龄大于18岁的user
        List<User> users = User.dao.find("select * from user where age>18");
        renderText(JsonKit.toJson(users));
    }

    public void paginate() {
        // 分页查询年龄大于18的user,当前页号为1,每页10个user
        Page<User> userPage = User.dao.paginate(1, 10, "select *", "from user where age > ?", 18);
        List<User> users = userPage.getList();
        renderText(JsonKit.toJson(users));
    }

    public void deleteById() {
        // 删除id值为25的User
        boolean result = User.dao.deleteById(25);
        renderText(String.valueOf(result));
    }


}
